package com.evolution.common.mybatis.listener;

import com.evolution.common.core.enums.HttpStatus;
import com.evolution.common.core.exception.ServiceException;
import com.evolution.common.mybatis.dataobject.BaseDO;
import com.mybatisflex.annotation.InsertListener;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * Class: DataObjectInsertListener
 * <p>
 * desc: 数据对象插入监听器
 * </p>
 * create date: 2024-03-07 12:28:05
 *
 * @author cao.yong
 */
public class DataObjectInsertListener implements InsertListener {
    @Override
    public void onInsert(Object entity) {
        try {
            if (Objects.nonNull(entity) && entity instanceof BaseDO baseDO) {
                LocalDateTime dateTime = Objects.nonNull(baseDO.getCreateTime()) ? baseDO.getCreateTime() : LocalDateTime.now();
                baseDO.setCreateTime(dateTime);
                baseDO.setUpdateTime(dateTime);
            }
        } catch (Exception e) {
            throw new ServiceException(HttpStatus.UNAUTHORIZED.getCode(), "全局插入数据监听器注入异常 => " + e.getMessage());
        }
    }
}
